import React, { useState, useEffect } from 'react';
import {
  Layout,
  List,
  Card,
  Button,
  Input,
  Tag,
  Space,
  Modal,
  Form,
  Select,
  Avatar,
  Dropdown,
  Menu,
  message,
  Tabs,
  TreeSelect,
  Tooltip,
  Divider,
  Popconfirm,
  Alert,
  Row,
  Col
} from 'antd';
import {
  MessageOutlined,
  LikeOutlined,
  EditOutlined,
  UserOutlined,
  ClockCircleOutlined,
  TagOutlined,
  FilterOutlined,
  SortAscendingOutlined,
  DeleteOutlined,
  MoreOutlined,
  ExclamationCircleOutlined,
  SearchOutlined,
  EyeOutlined
} from '@ant-design/icons';
import { useSelector, useDispatch } from 'react-redux';
import { useNavigate } from 'react-router-dom';
import { addPost, addComment, updatePost, deletePost, deleteComment } from '../../store/discussionSlice';
import discussionApi from '../../api/discussionApi';
import moment from 'moment';

const { Content, Sider } = Layout;
const { TextArea } = Input;
const { Option } = Select;
const { TabPane } = Tabs;

const DiscussionList = () => {
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [selectedCourse, setSelectedCourse] = useState(null);
  const [selectedCategory, setSelectedCategory] = useState('all');
  const [sortBy, setSortBy] = useState('latest');
  const [editingPost, setEditingPost] = useState(null);
  const [searchText, setSearchText] = useState('');
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const [discussions, setDiscussions] = useState([]);
  const [loading, setLoading] = useState(false);
  const [selectedDiscussion, setSelectedDiscussion] = useState(null);
  const [isDetailVisible, setIsDetailVisible] = useState(false);
  const currentUser = useSelector(state => state.user.currentUser);

  const dispatch = useDispatch();
  const { posts, loading: discussionLoading } = useSelector(state => state.discussion);
  const { courses } = useSelector(state => state.course);

  // 添加错误状态
  const [error, setError] = useState(null);

  // 帖子分类
  const categories = [
    { value: 'question', label: '课程疑问' },
    { value: 'share', label: '学习心得' },
    { value: 'resource', label: '资源分享' },
    { value: 'other', label: '其他' }
  ];

  useEffect(() => {
    fetchDiscussions();
  }, []);

  const fetchDiscussions = async () => {
    setLoading(true);
    try {
      const data = await discussionApi.getPublishedDiscussions();
      setDiscussions(data);
    } catch (error) {
      message.error('获取讨论列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 发布新帖子
  const handleCreatePost = (values) => {
    const newPost = {
      id: Date.now(),
      ...values,
      author: {
        id: currentUser.id,
        name: currentUser.username,
        avatar: currentUser.avatar
      },
      courseId: values.courseId,
      createTime: new Date().toLocaleString(),
      likeCount: 0,
      commentCount: 0,
      comments: []
    };

    dispatch(addPost(newPost));
    setIsModalVisible(false);
    form.resetFields();
    message.success('发布成功！');
  };

  // 点赞
  const handleLike = async (discussionId) => {
    try {
      await discussionApi.likeDiscussion(discussionId);
      message.success('点赞成功');
      fetchDiscussions();
    } catch (error) {
      message.error('点赞失败');
    }
  };

  // 添加评论
  const handleAddComment = (postId, content) => {
    if (!content.trim()) {
      message.warning('评论内容不能为空');
      return;
    }

    const newComment = {
      id: Date.now(),
      content,
      author: {
        id: currentUser.id,
        name: currentUser.username,
        avatar: currentUser.avatar
      },
      createTime: new Date().toLocaleString(),
      likeCount: 0
    };

    dispatch(addComment({ postId, comment: newComment }));
    message.success('评论成功！');
  };

  // 过滤帖子
  const filteredDiscussions = discussions.filter(discussion =>
    discussion.title.toLowerCase().includes(searchText.toLowerCase()) ||
    discussion.author.toLowerCase().includes(searchText.toLowerCase()) ||
    discussion.content.toLowerCase().includes(searchText.toLowerCase())
  );

  // 排序帖子
  const sortedDiscussions = [...filteredDiscussions].sort((a, b) => {
    switch (sortBy) {
      case 'latest':
        return new Date(b.createdAt) - new Date(a.createdAt);
      case 'popular':
        return b.likes - a.likes;
      case 'mostComments':
        return b.comments?.length - a.comments?.length;
      default:
        return 0;
    }
  });

  // 编辑帖子
  const handleEditPost = (post) => {
    setEditingPost(post);
    form.setFieldsValue({
      title: post.title,
      content: post.content,
      category: post.category
    });
    setIsModalVisible(true);
  };

  // 删除帖子
  const handleDeletePost = (postId) => {
    dispatch(deletePost(postId));
    message.success('帖子已删除');
  };

  // 删除评论
  const handleDeleteComment = (postId, commentId) => {
    dispatch(deleteComment({ postId, commentId }));
    message.success('评论已删除');
  };

  // 提交编辑
  const handleSubmitEdit = (values) => {
    if (editingPost) {
      dispatch(updatePost({
        postId: editingPost.id,
        updates: {
          title: values.title,
          content: values.content,
          category: values.category
        }
      }));
      message.success('帖子已更新');
    } else {
      handleCreatePost(values);
    }
    setIsModalVisible(false);
    setEditingPost(null);
    form.resetFields();
  };

  // 查看帖子详情
  const handleViewPost = (postId) => {
    navigate(`/discussion/${postId}`);
  };

  const handleViewDetail = (discussion) => {
    setSelectedDiscussion(discussion);
    setIsDetailVisible(true);
  };

  const PostItem = ({ post }) => {
    const isAuthor = currentUser?.id === post.author.id;
    const [commentForm] = Form.useForm();
    const [showComments, setShowComments] = useState(false);
    const [isHovered, setIsHovered] = useState(false);

    const menu = (
      <Menu>
        {isAuthor && (
          <>
            <Menu.Item key="edit" icon={<EditOutlined />} onClick={() => handleEditPost(post)}>
              编辑
            </Menu.Item>
            <Menu.Item
              key="delete"
              icon={<DeleteOutlined />}
              danger
              onClick={() => {
                Modal.confirm({
                  title: '确认删除',
                  icon: <ExclamationCircleOutlined />,
                  content: '确定要删除这个帖子吗？删除后将无法恢复。',
                  okText: '确定删除',
                  okType: 'danger',
                  cancelText: '取消',
                  onOk() {
                    handleDeletePost(post.id);
                  },
                });
              }}
            >
              删除
            </Menu.Item>
          </>
        )}
      </Menu>
    );

    return (
      <List.Item
        key={post.id}
        actions={[
          <Tooltip title="查看详情">
            <Button
              type="link"
              icon={<EyeOutlined />}
              onClick={() => handleViewDetail(post)}
            >
              查看详情
            </Button>
          </Tooltip>,
          <Space>
            <LikeOutlined />
            {post.likes || 0}
          </Space>,
          <Space>
            <MessageOutlined />
            {post.comments?.length || 0}
          </Space>
        ]}
      >
        <List.Item.Meta
          title={<a onClick={() => handleViewDetail(post)}>{post.title}</a>}
          description={
            <Space>
              <span>作者: {post.author}</span>
              <span>发布时间: {moment(post.createdAt).format('YYYY-MM-DD HH:mm')}</span>
              <Tag color="green">已发布</Tag>
            </Space>
          }
        />
        {post.content.length > 200 
          ? `${post.content.substring(0, 200)}...` 
          : post.content}
      </List.Item>
    );
  };

  return (
    <Layout>
      <Content style={{ padding: '0 24px', minHeight: 280 }}>
        <Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
          <Col xs={24} sm={12} md={8} lg={6}>
            <Input
              placeholder="搜索讨论..."
              prefix={<SearchOutlined />}
              onChange={e => setSearchText(e.target.value)}
              style={{ width: '100%' }}
            />
          </Col>
        </Row>

        {/* 搜索结果提示 */}
        {searchText && (
          <div style={{ marginBottom: 16, color: '#666' }}>
            搜索 "{searchText}" 的结果 ({sortedDiscussions.length} 条)
          </div>
        )}

        {/* 添加错误状态 */}
        {error && (
          <Alert
            message="加载失败"
            description={error}
            type="error"
            showIcon
            style={{ marginBottom: 16 }}
            action={
              <Button type="primary" onClick={() => window.location.reload()}>
                重新加载
              </Button>
            }
          />
        )}

        {/* 帖子列表 */}
        {loading ? (
          <Alert
            message="加载中..."
            type="info"
            showIcon
            style={{ marginBottom: 16 }}
          />
        ) : (
          <List
            loading={loading}
            dataSource={sortedDiscussions}
            renderItem={post => <PostItem post={post} />}
            pagination={{
              pageSize: 10,
              total: sortedDiscussions.length,
              showTotal: (total) => `共 ${total} 条讨论`,
              showQuickJumper: true,
              showSizeChanger: true
            }}
            locale={{
              emptyText: '暂无讨论',
              loading: '加载中...'
            }}
          />
        )}

        {/* 发帖/编辑对话框 */}
        <Modal
          title={editingPost ? "编辑帖子" : "发布帖子"}
          visible={isModalVisible}
          onCancel={() => {
            setIsModalVisible(false);
            setEditingPost(null);
            form.resetFields();
          }}
          footer={null}
        >
          <Form
            form={form}
            onFinish={handleSubmitEdit}
            layout="vertical"
            initialValues={editingPost ? {
              title: editingPost.title,
              content: editingPost.content,
              category: editingPost.category,
              courseId: editingPost.courseId
            } : {}}
          >
            <Form.Item
              name="title"
              label="标题"
              rules={[{ required: true, message: '请输入标题' }]}
            >
              <Input placeholder="请输入帖子标题" />
            </Form.Item>
            <Form.Item
              name="content"
              label="内容"
              rules={[{ required: true, message: '请输入内容' }]}
            >
              <TextArea rows={4} placeholder="请输入帖子内容" />
            </Form.Item>
            <Form.Item
              name="category"
              label="分类"
              rules={[{ required: true, message: '请选择分类' }]}
            >
              <Select placeholder="选择帖子分类">
                {categories.map(category => (
                  <Option key={category.value} value={category.value}>
                    {category.label}
                  </Option>
                ))}
              </Select>
            </Form.Item>
            <Form.Item
              name="courseId"
              label="来自课程"
              rules={[{ required: true, message: '请选择课程' }]}
            >
              <TreeSelect
                showSearch
                style={{ width: '100%' }}
                dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                placeholder="请选择课程"
                allowClear
                treeDefaultExpandAll
                treeData={courses.map(course => ({
                  title: course.title,
                  value: course.id,
                  key: course.id
                }))}
              />
            </Form.Item>
            <Form.Item>
              <Button type="primary" htmlType="submit" block>
                {editingPost ? "保存修改" : "发布"}
              </Button>
            </Form.Item>
          </Form>
        </Modal>

        <Modal
          title="讨论详情"
          open={isDetailVisible}
          footer={null}
          onCancel={() => setIsDetailVisible(false)}
          width={800}
        >
          {selectedDiscussion && (
            <div>
              <h2>{selectedDiscussion.title}</h2>
              <Space style={{ marginBottom: 16 }}>
                <span>作者: {selectedDiscussion.author}</span>
                <span>发布时间: {moment(selectedDiscussion.createdAt).format('YYYY-MM-DD HH:mm')}</span>
                <Button 
                  type="link" 
                  icon={<LikeOutlined />}
                  onClick={() => handleLike(selectedDiscussion.id)}
                >
                  点赞 ({selectedDiscussion.likes || 0})
                </Button>
              </Space>
              <div style={{ 
                marginTop: 16, 
                padding: 16, 
                background: '#f5f5f5', 
                borderRadius: 4 
              }}>
                <p style={{ whiteSpace: 'pre-wrap' }}>{selectedDiscussion.content}</p>
              </div>
            </div>
          )}
        </Modal>
      </Content>

      <Sider width={300} style={{ background: '#fff', padding: 24 }}>
        <Card title="讨论区指南">
          <ul style={{ paddingLeft: 20 }}>
            <li>选择相关课程进行讨论</li>
            <li>遵守社区规范，互相尊重</li>
            <li>分享有价值的学习经验</li>
            <li>标记合适的帖子分类</li>
            <li>使用搜索功能快速找到感兴趣的内容</li>
          </ul>
        </Card>
        <Card title="热门标签" style={{ marginTop: 16 }}>
          <Space wrap>
            {categories.map(category => (
              <Tag
                key={category.value}
                color="blue"
                style={{ cursor: 'pointer' }}
                onClick={() => setSelectedCategory(category.value)}
              >
                {category.label}
              </Tag>
            ))}
          </Space>
        </Card>
      </Sider>
    </Layout>
  );
};

export default DiscussionList; 